﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SQLPXBase.Factory.Keys;

namespace SQLPXBase.Factory.ChangeAwareness
{
    public class ChangingModelHash
    {
        private Dictionary<string, string> hash;

        public ChangingModelHash(Dictionary<string, string> hash)
        {
            this.hash = hash;
        }

        public static bool CheckForChanges(ChangingModelHash h1, ChangingModelHash h2)
        {
            if (h1 == null || h2 == null) return true;
            if (h1.hash == null || h2.hash == null) return true;

            if (h1.hash.Count != h2.hash.Count) return true;

            foreach (string k in h1.hash.Keys)
            {
                if (!h2.hash.ContainsKey(k)) return true;
                if (h1.hash[k] != h2.hash[k])
                    return true;
            }

            return false;
        }

        public static ChangingModelHash StandardModelSerialize<PX>(FactorizableModel<PX> model) where PX : SQLProxyBase, new()
        {
            Type t = model.GetType();
            PropertyInfo[] p = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            Dictionary<string, string> tmp = p.Where(property => property.CanRead && property.Name != "factory")
                .ToDictionary(
                    info => info.Name,
                    info =>
                        info.GetValue(model, null) is BaseLazyKey<PX>
                            ? ((BaseLazyKey<PX>) info.GetValue(model, null)).Id.ToString()
                            : (info.GetValue(model, null) ?? "").ToString()
                );
            return new ChangingModelHash(tmp);
        }
    }
}
